import type { DirectiveBinding, ObjectDirective } from "vue"

const map = new WeakMap()
const ob = new ResizeObserver(entries => {
  for (const entry of entries) {
    const handler = map.get(entry.target)
    if (handler) {
      const { inlineSize, blockSize } = entry.contentBoxSize[0]
      handler({ width: inlineSize, height: blockSize })
    }
  }
})

const Resize: ObjectDirective = {
  created(el: HTMLElement, binding: DirectiveBinding) {
    console.log(binding)
    map.set(el, binding.value);
    ob.observe(el);
  },
  beforeUnmount(el: HTMLElement) {
    ob.unobserve(el);
  },
};

export default {
  name: "resize",
  directive: Resize,
};